<template>
  <div>
    <div :id="echartsId" style="height: 300px; width: 100%"></div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  infoList: {
    type: Object,
    default: null,
  },
  series: {
    type: Array,
    default: () => [],
  },
  echartsTitle: {
    type: String,
    default: '',
  },
  yAxisData: {
    type: Array,
    default: () => [],
  },
  bingXdata: {
    type: Array,
    default: () => [],
  },
});

// 响应式变量 - 替代原 data
const echartsId = ref(`echarts-${Math.ceil(Math.random() * 10000)}`); // 更唯一的 ID
const myChart = ref(null); // 存储 ECharts 实例

const initChart = () => {
  // 确保 DOM 元素存在后再初始化
  nextTick(() => {
    const chartDom = document.getElementById(echartsId.value);
    if (!chartDom) return;

    // 销毁旧实例，避免重复创建
    if (myChart.value) {
      myChart.value.dispose();
    }

    myChart.value = echarts.init(chartDom);
    setChartOption(); // 设置图表配置项
  });
};

// 设置图表配置项
const setChartOption = () => {
  if (!myChart.value || !props.infoList) return;

  let option = null;

  // 饼图配置
  if (props.echartsTitle === 'circle') {
    option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'right',
        data: props.infoList.bing_xdata || [],
      },
      series: [
        {
          name: '访问来源',
          type: 'pie',
          radius: '70%',
          center: ['50%', '60%'],
          data: props.infoList.bing_data || [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    };
  } 
  // 折线图/柱状图配置
  else {
    option = {
      tooltip: {
        trigger: 'axis',
      },
      toolbox: {},
      legend: {
        data: props.infoList.legend || [],
      },
      color: ['#1495EB', '#00CC66', '#F9D249', '#ff9900', '#9860DF'],
      grid: {
        left: 16,
        right: 25,
        bottom: 10,
        top: 40,
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#D7DDE4',
            },
          },
          axisTick: {
            alignWithLabel: true,
            lineStyle: {
              color: '#D7DDE4',
            },
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: '#F5F7F9',
            },
          },
          axisLabel: {
            interval: 0,
            rotate: 40,
            color: '#7F8B9C',
          },
          data: props.infoList.xAxis || [],
        },
      ],
      yAxis: props.yAxisData.length
        ? props.yAxisData.map(axis => {
            // 如果 yAxisData 是从父组件传入的，也需要检查并修正
            if (axis.axisLabel && axis.axisLabel.textStyle) {
              // 将 textStyle 的属性提升到 axisLabel 一级
              Object.assign(axis.axisLabel, axis.axisLabel.textStyle);
              delete axis.axisLabel.textStyle;
            }
            return axis;
          })
        : {
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: '#7F8B9C', 
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#F5F7F9',
              },
            },
            type: 'value',
          },
      series: props.series || [],
    };
  }
  myChart.value.setOption(option, true);
};


// 监听 props 变化，更新图表
watch(
  () => [props.infoList, props.series],
  () => {
    if (myChart.value) {
      setChartOption();
    } else {
      initChart();
    }
  },
  { deep: true } // 深度监听对象/数组内部变化
);

const handleResize = () => {
  if (myChart.value) {
    myChart.value.resize();
  }
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时销毁图表和事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (myChart.value) {
    myChart.value.dispose();
    myChart.value = null;
  }
});

// 暴露给父组件的方法（保持原功能）
defineExpose({
  handleResize,
});
</script>

<style scoped></style>